import gevent
import threading
from task_queue import TASK_QUEUE

class MyThread(threading.Thread):
    def __init__(self, call_func):
        super(MyThread, self).__init__()
        self.call_func = call_func

    def run(self):
        self.call_func()


def foo(message, n):
    for i in range(8):
        print("thread: {}---message: {}".format(threading.get_ident(), message))
        gevent.sleep(n)
        TASK_QUEUE.add_task(foo_end, message)


def foo_end(message):
    print("thread: {}---message: {} end".format(threading.get_ident(), message))


def start_test1():
    spawn1 = gevent.spawn(foo, "Hello", 1)
    spawn2 = gevent.spawn(foo, "I live!", 2)
    spawn3 = gevent.spawn(foo, "I live! 3", 1)
    spawn4 = gevent.spawn(foo, "I live! 4", 2)
    spawn5 = gevent.spawn(foo, "I live! 5", 1)

    spawns = [spawn1, spawn2, spawn3, spawn4, spawn5]
    gevent.joinall(spawns)


def start_test2():
    spawn1 = gevent.spawn(foo, "Hello2", 1)
    spawn2 = gevent.spawn(foo, "I live!2", 2)

    spawns = [spawn1, spawn2]
    gevent.joinall(spawns)

if __name__ == "__main__":
    th1 = MyThread(start_test1)
    th2 = MyThread(start_test2)

    th2.start()
    th1.start()
    
    

    th1.join()
    th2.join()
    TASK_QUEUE.shutdown()
    TASK_QUEUE.join()
